<?php
/*
 * This file is part of the BooXtore Student project.
 *
 * (c) Francis Backeland f.backeland@gmail.com
 * (c) Laurine Chaplot chaplot.laurine@orange.fr
 * (c) Julien Dutot julien.dutot@gmail.com
 * (c) Romain Guillaume romain-guillaume@orange.fr
 * (c) Guillaume Paringaux g.paringaux@gmail.com
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code
 * 
 */

namespace BXTR\UserBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use BXTR\UserBundle\Entity\User;
use BXTR\UserBundle\Entity\Role;

class AddUserCommand extends ContainerAwareCommand
{
    public function configure()
    {
        $this
            ->setName('bxtr:user:add')
            ->setDescription('Create an user')
            ->addArgument('name', InputArgument::REQUIRED, 'The name of the new user.')
            ->addArgument('password', InputArgument::REQUIRED, 'The password of the new user.')
            ->addOption('role', 'r', InputOption::VALUE_OPTIONAL, 'Specify a role to the user.')
        ;
    }

    protected function execute(InputInterface $in, OutputInterface $out)
    {
        $name = $in->getArgument('name');
        $password  = $in->getArgument('password');

        $container = $this->getContainer();

        $em = $container->get('doctrine')->getManager();
        $user = $em->getRepository('BXTRUserBundle:User')
            ->findOneByUsername($name);

        if (!$user) {
            $user = new User();
        }

        $user->setUsername($name);
        $user->setMail($name . '@email.tld');
        $user->setDateSubscribe(new \DateTime());

        $encoder = $container->get('security.encoder_factory')
            ->getEncoder($user);

        $encodedPassword = $encoder->encodePassword($password, $user->getSalt());
        $user->setPassword($encodedPassword);

        $roleName = $in->getOption('role');

        $out->writeln($roleName);
        if ($roleName) {
            $role = $em->getRepository('BXTRUserBundle:Role')
                ->findOneByRole($roleName);

            if (!$role) {
                $role = new Role();
                $role->setRole($roleName);
                $role->setLabel($roleName);
            }

            $user->setDbRole($role);
            $em->persist($role);
        }

        $em->persist($user);
        $em->flush();

        $out->writeln('user ' . $name . ' created.');
    }
}
